package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.SpecClass;
import cn.imvc.app.repositories.SpecClassRepository;
import cn.imvc.data.domain.ViewRequest;
/**
 * 
 * @author zhy
 * @date 2016年7月28日上午10:17:21
 *
 */
@Service
public class SpecClassModelImpl implements SpecClassModel{
    
	@Autowired
	SpecClassRepository specClassRepository;
	@Autowired
	RefRelationModel refRelationModel;
	
	public Page<SpecClass> find(ViewRequest viewRequest) {
		
		return specClassRepository.findAll(viewRequest);
	}

	public SpecClass get(int id) {
		
		return specClassRepository.getOne(id);
	}

	public int save(SpecClass specClass) {
		
		String code = specClass.getCode();
		String name = specClass.getName();
		List<SpecClass> sc = specClassRepository.getByCode(code);
		List<SpecClass> sn = specClassRepository.getByName(name);
		if(sc.size()>0){
			return 0;
		}
		if(sn.size()>0){
			return -1;
		}
		specClassRepository.saveAndFlush(specClass);
		return 1;
	}

	public int update(int id, SpecClass specClass) {
		SpecClass loadSpecClass = specClassRepository.getOne(id);
		String code = specClass.getCode();
		String name = specClass.getName();
		List<SpecClass> sc = specClassRepository.getByCode(code);
		List<SpecClass> sn = specClassRepository.getByName(name);
		if(sc.size()>0&&!code.equals(loadSpecClass.getCode())){
			return 0;
		}
		if(sn.size()>0&&!name.equals(loadSpecClass.getName())){
			return -1;
		}
		BeanUtils.copyProperties(specClass, loadSpecClass, new String[]{"id"});
		specClassRepository.saveAndFlush(loadSpecClass);
		return 1;
	}

	public String delete(int id) {
		 String result = refRelationModel.deleteDateCheck("Spec_Class", "id", id);
		    if(result.equals("")){
		    	specClassRepository.delete(id);
		    	return "";
		    }else{
		    	return result;
		    }
	}

	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			specClassRepository.delete(id);
		}
	}

}
